#include <stdio.h>
#include "FindWay.h"

static CPoint stack[512];
static int top = 0;

int maze[MAX_ROW][MAX_COL] =
{
	{0, 1, 0, 0, 0},
	{0, 1, 0, 1, 0},
	{0, 0, 0, 0, 0},
	{0, 1, 1, 1, 0},
	{0, 0, 0, 1, 0}
};

void push(CPoint p)
{
	stack[top++] = p;
}

CPoint pop(void)
{
	return stack[--top];
}

int is_empty(void)
{
	return top == 0;
}


struct CPoint predecessor[MAX_ROW][MAX_COL] =
{
	{{ -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}},
	{{ -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}},
	{{ -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}},
	{{ -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}},
	{{ -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}, { -1, -1}},
};

void print_maze(void)
{
	int i, j;
	for (i = 0; i < MAX_ROW; i++)
	{
		for (j = 0; j < MAX_COL; j++)
			printf("%d ", maze[i][j]);
		putchar('\n');
	}
	printf("****************************************\n");
}


void visit(int row, int col, struct CPoint pre)
{
	struct CPoint visit_point = { row, col };
	maze[row][col] = 2;
	predecessor[row][col] = pre;
	push(visit_point);
}

int FindWayOut(void)
{
    //Visit the start point first, and push it into stack.
	struct CPoint p = { 0, 0 };
	maze[p.row][p.col] = 2;
	push(p);

	while (!is_empty())
	{
		p = pop();

		if (p.row == MAX_ROW - 1 /* goal */ && p.col == MAX_COL - 1)
			break;

		if (p.col + 1 < MAX_COL /* right */ && maze[p.row][p.col + 1] == 0)
			visit(p.row, p.col + 1, p);

		if (p.row + 1 < MAX_ROW /* down */ && maze[p.row + 1][p.col] == 0) 
			visit(p.row + 1, p.col, p);

		if (p.col - 1 >= 0 /* left * */ && maze[p.row][p.col - 1] == 0)
			visit(p.row, p.col - 1, p);

		if (p.row - 1 >= 0 /* up * */ && maze[p.row - 1][p.col] == 0)
			visit(p.row - 1, p.col, p);

		print_maze();
	}

	if (p.row == MAX_ROW - 1 && p.col == MAX_COL - 1)
	{
		printf("(%d, %d)\n", p.row, p.col);
		while (predecessor[p.row][p.col].row != -1)//初始化为-1, 所以根结点的前任就是-1, 因些作为循环结束的条件.
		{
			p = predecessor[p.row][p.col]; printf("(%d, %d)\n", p.row, p.col);
		}
	}
	else
	{
		printf("No path!\n");
	}

	return 0;
}
